package com.sf.proxy.server;

import com.sf.proxy.handler.UdpPacketHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

public class UdpServer {

    public void start(int port) {
        NioEventLoopGroup worker = new NioEventLoopGroup(1, new DefaultThreadFactory("work", Thread.MAX_PRIORITY));
        NioEventLoopGroup boss = new NioEventLoopGroup(1, new DefaultThreadFactory("boss", Thread.MAX_PRIORITY));
        try {
            Bootstrap b = new Bootstrap();
            b.group(boss)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) {
                            ch.pipeline().addLast("udp-packet-handler", new UdpPacketHandler());
                        }
                    });
            ChannelFuture f = b
                    .bind(port)
                    .sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }


}
